package services;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;



public abstract class AbstractService {
	
	static public ThreadLocal<Session>  tl = new ThreadLocal<Session>();
	static SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
	
	public void execute() {
		
		Session session = sessionFactory.openSession();
		tl.set(session);
		Transaction transaction = session.beginTransaction();
				
		try {
			this.doYourMagic();
			session.flush();
			transaction.commit();
		}
		catch(RuntimeException e) {
			transaction.rollback();
			throw e;
		}
		finally {
			session.close();
			tl.set(null);
		}
		
	}
	
	public abstract void doYourMagic();
}
